package com.haliyoo.adhs.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import com.haliyoo.adhs.dao.AdInfoDao;
import com.haliyoo.adhs.exception.DaoLevelException;
import com.haliyoo.adhs.model.AdInfo;
import com.haliyoo.adhs.model.User;

public class AdInfoDaoImpl implements AdInfoDao {
	
	private static final Logger	logger	= Logger.getLogger(AdInfoDaoImpl.class);
	
	private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }
    @SuppressWarnings("unchecked")
    public List<AdInfo> findAll() throws DaoLevelException {
        List<AdInfo> adInfoList = null;
    	try{
	        Query query = getEntityManager().createQuery("select p FROM AdInfo p");
	        adInfoList = query.getResultList();
	        
	    }catch(Exception e){
	    	throw new DaoLevelException("error -- List<AdInfo> findAll()",e);
	    }
	    return adInfoList;
        
        
    }

    public void save(AdInfo adInfo) throws DaoLevelException {
	        if (adInfo.getId() == null) {
	        	adInfo.setCreateTime(new Date());
	        	try{
	        		adInfo.setCreateTime(new Date());
		            em.persist(adInfo); // new
		        }catch(Exception e){
			    	logger.error(e.getMessage(),e);
			    	throw new DaoLevelException("error -- save(AdInfo adInfo) -- em.persist(adInfo)",e);
				}
	        } else {
	        	try{
		            em.merge(adInfo); // update
		        }catch(Exception e){
			    	logger.error(e.getMessage(),e);
			    	throw new DaoLevelException("error -- save(AdInfo adInfo) -- em.merge(adInfo)",e);
				}
	        }
	    
    }

    public void remove(AdInfo adInfo) throws DaoLevelException {
        if (adInfo != null) {
        	try{
	            em.remove(em.merge(adInfo));
	        }catch(Exception e){
		    	logger.error(e.getMessage(),e);
		    	throw new DaoLevelException("error -- remove(AdInfo adInfo)",e);
	    	}
        }
    }

    private EntityManager getEntityManager() {
        return em;
    }

    public AdInfo find(Integer id) throws DaoLevelException {
    	
		AdInfo adInfo = null;
    	try{
    		adInfo = em.find(AdInfo.class, id);
    	}catch(NoResultException e){
	    	logger.error(e.getMessage(),e);
	    	throw new DaoLevelException("error -- find(Integer id)",e);
    	}
        return adInfo;
    }
}